package org.aom.litebean.module.base;

import java.io.Serializable;

import org.aom.service.base.IEntityManager;
import org.operamasks.faces.component.grid.GridColumn;
import org.operamasks.faces.component.grid.SortDirection;
import org.operamasks.faces.component.grid.impl.UIDataGrid;
import org.operamasks.faces.component.grid.provider.GridDataProvider;

public abstract class SimpleListBean<T, PK extends Serializable> extends
		BeforeRenderBaseBean {

	protected abstract Class<T> getEntityClass();

	protected abstract IEntityManager<T, PK> getEntityManager();

	protected abstract UIDataGrid getDataGrid();

	protected abstract String getIdColumn();

	@SuppressWarnings("serial")
	public GridDataProvider getDataProvider() {
		return new GridDataProvider() {
			private Object[] objs;

			// 当不再集成这个父类的时候最好能够定制方法，以免某些东东在View
			// Layer中出现

			public Object[] getElementsById(String[] ids) {
				return getEntityManager().getElementsById(ids).toArray();
			}

			public Object[] getElements() {
				if (objs == null) {
					objs = getEntityManager().getElements(start, limit,
							getIdColumn(), true).toArray();
				}
				return objs;
			}

			public int getTotalCount() {
				return getEntityManager().totalCount();
			}

			public void sort(final GridColumn column,
					final SortDirection direction) {
				String sortName = column.getId();
				objs = getEntityManager().getElements(start, limit, sortName,
						direction.equals(SortDirection.ASC)).toArray();
			}
		};
	}
}
